<template>
  <view class="home">
    <view>
      <view class="headerContainer">
        <view class="headerWrap">
          <div class="userInfo">
            <u-avatar
              :src="userImg"
              size="110"
              @click="imgView"
            />
            <div class="hello_user">
              <div class="name">{{ hi }}， {{ name }}!</div>
              <div class="hi">wwwwwwwwwwwwww案</div>
            </div>
          </div>
          <!-- 用户做的单子的信息 -->
          <Show-Progress :unit="'单位:万元'" :do-info-list="doInfoList" />
        </view>
      </view>
      <view class="home-container">
        <Home-Content :list="homeLayoutList" :count="sp" @layoutClick="layoutClick" />
      </view>
      <u-select
        v-model="changeRole.show"
        mode="mutil-column-auto"
        :list="changeRole.list"
        :default-value="changeRole.default"
        safe-area-inset-bottom
        @confirm="changeRoleConfirm"
      />
      <view class="home-change" @click="changeRole.show = true">切换系统/角色/乡镇 {{ changeRole.roleNow }}</view>
      <!-- <view @click="$router.push('/404')">go 404</view> -->

    </view>
  </view>
</template>

<script>
import ShowProgress from './components/ShowProgress';
import HomeContent from './components/HomeContent';
import { getHomeSummery, getList } from '@/api/task';
import { setLocal, getLocalStorage } from '@/utils/utils';
import getConfig from '@/server/getConfig.js';
import { setAppId, getAppId } from '@/utils/local.js';
import { api as viewerApi } from 'v-viewer';

const findItemByKey1 = function(target, key, value, res) {
  if (Array.isArray(target)) {
    for (let i = 0; i < target.length; i++) {
      findItemByKey(target[i], key, value, res);
    }
  } else {
    if (target[key] === value) {
      res.value = target;
      return target;
    } else {
      const c = target.children;
      if (Array.isArray(c) && c.length) {
        return findItemByKey(c, key, value, res);
      }
    }
  }

  return false;
};

const findItemByKey = function(target, key, value, res) {
  res = res || {};
  findItemByKey1(target, key, value, res);
  return res.value;
};

export default {
  components: {
    ShowProgress,
    HomeContent
  },
  data() {
    return {
      name: '',
      userImg: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2Fc8%2Fdd%2Fb9%2Fc8ddb934a69d90216f1b406cf3975475.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629892402&t=98e4b73d556d0b43fdcf1f3b3030a574',
      hi: '',
      roleIdList: [],
      mEnterprise: [],
      // 显示进度（预算数...）
      doInfoList: [
        {
          name: '预算数',
          total: '-'
        },
        {
          name: '已拨付',
          total: '-'
        },
        {
          name: '执行率',
          total: '-'
        }
      ],

      homeLayoutList1: [
        {
          title: '任务库',
          desc: '项目跟踪 实时汇报',
          type: 'task', // 将要跳转页面
          url: 'aaa/bbb',
          img: require('@/static/img/home/home-task.png'),
          params: {
            aaa: 'cqc'
          }
        },
        {
          title: '汇总分析',
          desc: '这是描述字符',
          img: require('@/static/img/home/home-all.png'),
          type: 'SummaryAnalysis', // 将要跳转页面
          url: 'aaa/bbb',
          params: {
            aaa: 'cqc'
          }
        },
        {
          title: '资金监管',
          desc: '这是描述字符',
          img: require('@/static/img/home/home-file.png'),
          type: '/township', // 将要跳转页面
          url: 'aaa/bbb',
          params: {
            aaa: 'cqc'
          }
        },
        {
          title: '项目分析',
          desc: '这是描述字符',
          img: require('@/static/img/home/home-fx.png'),
          type: '/township', // 将要跳转页面
          url: 'aaa/bbb',
          params: {
            aaa: 'cqc'
          }
        },
        {
          title: '预警',
          desc: '这是描述字符',
          img: require('@/static/img/home/home-yj.png'),
          type: 'list', // 将要跳转页面
          url: 'aaa/bbb',
          params: {
            aaa: 'cqc'
          }
        },
        {
          title: '模板库',
          desc: '这是描述字符',
          img: require('@/static/img/home/home-yj.png'),
          type: 'list', // 将要跳转页面
          url: 'aaa/bbb',
          params: {
            aaa: 'cqc'
          }
        },
        {
          title: '统计中心',
          desc: '这是描述字符',
          img: require('@/static/img/home/home-yj.png'),
          type: 'StatisticCenterList', // 将要跳转页面
          url: 'aaa/bbb',
          params: {
            aaa: 'cqc'
          }
        }
        /* {
          title: '模板库',
          desc: '这是描述字符',
          img: require('@/static/img/home/home-file.png'),
          type: 'list', // 将要跳转页面
          url: 'aaa/bbb',
          params: {
            aaa: 'cqc'
          }
        } */
      ],

      homeLayoutList: [],

      // 切换
      changeRole: {
        roleNow: '',
        show: false,
        default: [],
        list: [
          {
            label: '切换角色',
            value: '角色',
            children: []
          },
          {
            label: '切换乡镇',
            value: '乡镇',
            children: []
          }
        ]
      },
      sp: 0,
      czRole: false
    };
  },
  created() {
    this.init();
    setTimeout(async() => {
      if (getLocalStorage('dType') === 'zdd' || this.$route.query.dType === 'zdd') {
        let bid = '';
        await getConfig().then(res => {
          bid = res.data.bid;
        });
        // 稳定性监控
        try {
          const config = {
            bid: bid,
            signkey: '1234567890abcdef',
            gateway: 'https://wpk-gate.zjzwfw.gov.cn'
          };
          const wpk = new wpkReporter(config);
          wpk.installAll();
          window._wpk = wpk;
        } catch (err) {
          console.error('WpkReporter init fail', err);
        }
      }
    }, 2000);
  },
  methods: {
    init() {
      this.getHomeContent();
      this.collectRoles();
      this.getHomeSummery();
      this.getUserAvatar();
      this.getHomeContent();
    },

    getHomeContent() {
      getConfig().then(({ data }) => {
        const { homeContent } = data;
        if (homeContent) {
          const content = homeContent.split(',');
          this.homeLayoutList = this.homeLayoutList1.filter(o => {
            return content.includes(o.title);
          });
        }
      });
    },

    getUserAvatar() {
      const userImg = getLocalStorage('userAvatar');
      if (userImg) {
        this.userImg = userImg;
      }

      window.addEventListener('userAvatar', e => {
        this.userImg = e.value;
      });
    },

    imgView() {
      viewerApi(
        {
          options: {
            navbar: false,
            title: false
          },
          images: [this.userImg]
        }
      );
    },

    changeRoleConfirm(e) {
      const [{ value: value1 }, { value: value2, label: label2 }, { value: value3 }] = e;
      if (value1 === '角色') {
        // value2 appId
        setAppId(value2);
        setLocal({ appRole: value3 });
        const item = findItemByKey(this.roleIdList, 'name', value3);
        if (item) {
          setLocal({ appRoleId: item.id });
        }
      } else if (value1 === '乡镇') {
        setLocal({ mIsbnCode: value2 });
        setLocal({ mIsbnCodeName: label2 });
        const item = findItemByKey(this.mEnterprise, 'label', label2);
        if (item) {
          setLocal(
            { mEnterpriseId: item.id }
          );
        }
      }
      this.$router.go(0);
    },

    // 收集角色身份
    collectRoles() {
      try {
        const value = getLocalStorage('appRole');
        const roleIdList = getLocalStorage('appUserQx');
        const mEnterprise = getLocalStorage('mEnterprise');
        const userName = getLocalStorage('userName');
        const appNowIdx = roleIdList.findIndex(item => {
          return (item.value + '') === (getAppId() + '');
        });

        this.roleIdList = roleIdList;
        this.mEnterprise = mEnterprise;
        if (appNowIdx > -1) {
          const roleIdx = roleIdList[appNowIdx].children.findIndex(item => {
            return item.value === value;
          });

          this.changeRole.default = [0, appNowIdx, roleIdx];
        }

        const timeHour = new Date().getHours();
        if (timeHour >= 0 && timeHour < 12) {
          this.hi = '上午好';
        } else if (timeHour >= 12 && timeHour < 18) {
          this.hi = '下午好';
        } else {
          this.hi = '晚上好';
        }

        this.name = userName;

        if (mEnterprise) {
          mEnterprise.forEach(item => {
            // 没绑乡镇 item 就是 ''
            if (item) {
              item.children = [];
            }
          });
        }

        this.changeRole.list[0].children = roleIdList;
        this.changeRole.list[1].children = mEnterprise;
        if (value) {
          this.changeRole.roleNow = value;
        } else {
          uni.showToast({
            title: '未查询到角色相关消息',
            duration: 2000,
            icon: 'none'
          });
        }
      } catch (e) {
        // error
        console.log(e);
      }

      /* uni.getStorage({
        key: 'roleList',
        complete: res => {
          if (res.errMsg !== 'getStorage:fail') {
            res.data.forEach((item, index) => {
              item.label = item.name;
              item.value = index;
            });
            this.changeRole.list[0].children = res.data;
          }
        }
      }); */
    },

    getHomeSummery() {
      const appRole = uni.getStorageSync('appRole');
      const userId = uni.getStorageSync('userId');
      this.czRole = appRole && appRole.includes('财政');
      getHomeSummery({
        userId: this.czRole ? userId : undefined
      }).then(res => {
        const { success, data } = res;
        if (success) {
          const { isjMoney, fkhj, sjzxl } = data;
          this.doInfoList.forEach(item => {
            if (item.name === '预算数') {
              item.total = isjMoney;
            } else if (item.name === '已拨付') {
              item.total = fkhj;
            } else if (item.name === '执行率') {
              item.total = sjzxl;
            }
          });
          this.czRole && (this.sp = data.sp);
        }
      });
    },
    layoutClick(item) {
      const { url, title, type } = item;
      const params = `?url=${url}&title=${title}`;
      if (title === '资金监管' || title === '项目分析') {
        this.$router.replace(`${type}${params}`);
      } else {
        this.$router.push(`${type}${params}`);
      }
    }
  }
};
</script>

<style scoped lang='scss'>
	.contentMain /deep/.u-badge {
		display: -webkit-inline-box;
		display: -webkit-inline-flex;
		display: inline-flex;
		-webkit-box-pack: center;
		-webkit-justify-content: center;
		justify-content: center;
		-webkit-box-align: center;
		-webkit-align-items: center;
		align-items: center;
		line-height: 12px;
		padding: 3px 6px !important;
		-webkit-border-radius: 50px;
		border-radius: 50px;
		z-index: 9;
	}

	.headerContainer {
		width: calc(100vw);
		height: 178px;
		background: url('../../static/img/beijing.png') center center / cover no-repeat;
	}

	.headerWrap {
		padding-top: 60px;
		// padding-top: 122px;
		padding-left: 15px;
    margin-right: 15px;

    .userInfo {
      height: 60px;
      display: flex;
      align-items: center;
      position: relative;
      color: #FFFFFF;
      .hello_user {
        height: 100%;
        margin: 10px;
        margin-top: 25px;
        .name {
          margin-bottom: 3px;
        }
      }
    }
	}

	.home-container {
		margin-top: 90px;
		padding: 0 15px;
    &::after {
      content: '';
      display: block;
      width: 100%;
      height: 30px;
    }
	}

  .home-change {
    position: absolute;
    left: 15px;
    top: 12px;
    color: #fff;
    padding: 6px;
  }

</style>
